<script lang="ts" setup>
    import { onLaunch } from '@dcloudio/uni-app'
    import Func from '@/utils/functions'
    import Settings from '@/config/settings'
    import Constants from '@/utils/constants'
    import LocalStorage from '@/utils/localstorage'
    import { useGlobalStore } from '@/stores/global'
    import { appVersionShow, userUpdate, userShow } from '@/stores/service'

    const global = useGlobalStore()
    const loadAppVersion = async () => {
        try {
            const version = await Func.getVersion()
            global.version = version?.ver || ''
            const res = await appVersionShow({ version: global.version, code: version.code || '', os: plus.os.name })
            if (res?.code === Constants.API_SUCCESS) {
                global.upgrade.ver = res.data?.version || ''
                global.upgrade.url = res.data?.url || ''
                global.upgrade.type = res.data?.type || 0
                global.upgrade.desc = res.data?.desc || []
            }
            global.upgrade.time = Date.now()
        } catch (e) {
            console.log(e)
        } finally {
        }
    };

    const loadUser = async () => {
        try {
            const res = await userShow()
            if (res?.code === Constants.API_SUCCESS) {
                if (res.data?.id) {
                    global.setUser(res.data)
                }
            }
        } catch (error) {
            console.log(error)
        }
    };

    //监听检查版本更新事件
    uni.$on('checkVersionUpgradeEvent', async params => {
        if (typeof params == 'function') {
            await loadAppVersion()
            params()
        }
    });

    //监听全局更新用户信息事件
    uni.$on('refreshUserEvent', async params => {
        if (typeof params == 'function') {
            await loadUser()
            return params()
        }
        loadUser()
    })

    onLaunch(async (options) => {
        try {
            // #ifdef APP-PLUS
            plus.screen.lockOrientation("portrait-primary");
            // #endif

            const loadDeviceInfo = () => {
                const clientinfo = plus.push.getClientInfo()
                global.client_id = clientinfo.clientid
                global.device_token = clientinfo.token
                // plus.device.setWakelock(true)//TODO DEBUG
            };

            //监听系统通知栏消息点击事件  
            plus.push.addEventListener('click', async function (msg) {
                //处理点击消息的业务逻辑代码
                // console.log(msg, 'click event...')
                if (msg?.payload?.click_action == 'navigate_order') {
                    Func.switchTab({ url: '/pages/order/order' })
                }
            }, false);
            //监听接收透传消息事件
            //监听在线消息事件  
            plus.push.addEventListener("receive", function (msg) {
                // console.log(msg, 'receive event...')
                if (msg?.aps) {  // Apple APNS message  
                    //APNS下发的消息，应用在前台  
                } else if (msg?.payload?.from == 'local') {   //特殊payload标识本地创建的消息  
                    //本地创建的消息，通常不需要处理  
                    //注意：不要在这种情况下再此调用plus.push.createMessage，从而引起循环创建本地消息  
                } else {
                    //接收到在线透传消息  
                    let con = msg?.content || {}
                    if (typeof con == 'string') {
                        con = JSON.parse(con)
                    }
                    const options = { cover: false, sound: 'system' }//华为没效果
                    con.from = 'local'
                    if (typeof con?.badge != 'undefined' && !isNaN(con?.badge)) {
                        plus.runtime.setBadgeNumber(Number(con.badge))

                    }
                    if (con?.sound && global.user?.is_play) {
                        options.sound = 'none'
                        const innerAudioContext = uni.createInnerAudioContext()
                        innerAudioContext.autoplay = true
                        innerAudioContext.src = `/static/sound/${con.sound}.mp3`;
                        innerAudioContext.onPlay(() => {
                            console.log('开始播放');
                        });
                        innerAudioContext.onError((res) => {
                            console.log(res.errMsg);
                            console.log(res.errCode);
                        })
                    }
                    /* if(typeof con?.cover != 'undefined'){
                        options.cover = Boolean(con.cover)
                    } */
                    if (con?.is_notice) {
                        plus.push.createMessage(con.body, con, options)
                    }
                }
                //其它逻辑  
            }, false);

            ['navigateTo', 'redirectTo', 'reLaunch', 'switchTab', 'navigateBack'].forEach(name => {
                uni.addInterceptor(name, {
                    invoke(args) {
                        try {
                            if (!global?.client_id || global.client_id == 'null') {
                                loadDeviceInfo()
                            }
                            if (global.user?.id && global.user?.client_id != global.client_id) {
                                userUpdate({
                                    action: 'update_cid',
                                    client_id: global.client_id,
                                    device_token: global.device_token
                                }).then(res => {
                                    if (res?.code == Constants.API_SUCCESS) {
                                        loadUser()
                                    }
                                }).catch(e => {
                                    console.log(e)
                                })
                            }
                        } catch (e) {
                            console.info(e)
                        }
                        return true
                    },
                    returnValue(args) {
                    }
                })
            })

            uni.addInterceptor('request', {
                invoke(args) {
                    //拦截前
                    args.header = args.header || {}
                    args.header.appid = Settings.appid
                    args.url = Settings.domain + Settings.apiPath + args.url
                    //token
                    const headerToken = LocalStorage.getToken()
                    let _t = ''
                    if (headerToken) {
                        if (Settings.tokenType == 'Authorization') {
                            const { token, token_type } = headerToken
                            _t = token_type + ' ' + token
                        }
                        args.header = { ...args.header, [Settings.tokenType]: _t };
                    } else {
                        //api白名单由后端负责，通过API返回的CODE确定是否跳转login页面，前端只负责访问页面时权限的检查
                    }
                    // console.log(args)
                },
                async returnValue(args) {
                    const res = await args
                    // console.warn(res)
                    if (res?.data?.token?.token) {
                        LocalStorage.setToken(res.data.token)
                    }
                    if (res?.data?.code && [Constants.TOKEN_MISS, Constants.CLIENT_NOT_LOGIN, Constants.TOKEN_EXPIRE, Constants.TOKEN_ERROR].includes(res?.data?.code)) {
                        LocalStorage.removeToken()
                        if ('/' + getCurrentPages().pop()?.route != Settings.loginPath) {
                            return Func.redirectTo({
                                url: Settings.loginPath
                            })
                        }
                    }
                    if (args?.errMsg == 'request:fail abort statusCode:-1 timeout') {
                        throw { code: Constants.CLIENT_REQUEST_TIMEOUT, msg: 'client request timeout' }
                    }
                    return res.data
                }
            })
            uni.addInterceptor('uploadFile', {
                invoke(args) {
                    //拦截前
                    args.header = args.header || {}
                    args.header.appid = Settings.appid
                    //token
                    const headerToken = LocalStorage.getToken()
                    let _t = ''
                    if (headerToken) {
                        if (Settings.tokenType == 'Authorization') {
                            const { token, token_type } = headerToken
                            _t = token_type + ' ' + token
                        }
                        args.header = { ...args.header, [Settings.tokenType]: _t };
                    } else {
                        //api白名单由后端负责，通过API返回的CODE确定是否跳转login页面，前端只负责访问页面时权限的检查
                    }
                },
                async returnValue(args) {
                    const res = await args
                    const data = res?.data ? JSON.parse(res.data) : {}
                    if (data?.token?.token) {
                        LocalStorage.setToken(data.token)
                    }
                    if (data?.code && [Constants.TOKEN_MISS, Constants.CLIENT_NOT_LOGIN, Constants.TOKEN_EXPIRE, Constants.TOKEN_ERROR].includes(data?.code)) {
                        LocalStorage.removeToken()
                        if ('/' + getCurrentPages().pop()?.route != Settings.loginPath) {
                            return Func.redirectTo({
                                url: Settings.loginPath
                            })
                        }
                    }
                    if (args?.errMsg == 'request:fail abort statusCode:-1 timeout') {
                        throw { code: Constants.CLIENT_REQUEST_TIMEOUT, msg: 'client request timeout' }
                    }
                    return data
                }
            })
        } catch (e) {
            console.info(e)
        }
    })
</script>

<style>
    /*每个页面公共css */
    /* icon color #b3b3b3 */
    /* #ifdef APP-NVUE */
    /* #endif */
    /* #ifdef APP-VUE */
    page {
        background: #F8F8F8;
    }

    .nav-status-bar {
        height: var(--status-bar-height);
    }

    /* #endif */
</style>